﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.DALFactory;
using ECCIT;
using ECCIT.Business.Model;
using System.Linq;
using OgilvyOne.UKNow.IDAL;
using OgilvyOne.UKNow.DAL;
using OgilvyOne.UKNow.ServiceReference;
using OgilvyOne.Model;
using OgilvyOne.Utility;
using OgilvyOne.BLL;
using Lucene.Net.Documents;

namespace OgilvyOne.UKNow.BLL
{
    public class EventsBLL : IGenerateHtml
    {
        public int LanguageID { get; set; }
        public EventsBLL(int langID)
        {
            this.LanguageID = langID;
        }

        //新增活动
        public ResultInfo Save(EventsModel info)
        {
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.Save(info);
        }
        //获取所有活动
        public IList<EventsModel> selectevents()
        {
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetAllEventsModels();
        }
        //mff
        //根据所选语言,获取不重名的活动
        public List<EventsModel> seleventsByName(int langid)
        {
            this.LanguageID = langid;
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetEventModelsByName(langid);
        }
        //mff
        //根据所选语言和活动名称,获取活动的ID
        public IList<EventsModel> selEveByNandL(int langid,string eventName)
        {
            this.LanguageID = langid;
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetEveByNandL(langid, eventName);
        }
        //mff
        //获取特色活动
        public IList<EventsModel> selectevents(int isSpecial)
        {
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetAllEventsModels(isSpecial);
        }
        /*修改人：穆凤凤
        * 修改时间：2012-03-05
        * 修改内容：
        *      新增加方法 获得按姓名查找出来的活动实体 selEventByName
        *      有mff注释的为本次修改的代码
        */
        //mff
        //按活动名称搜索活动记录
        public IList<EventsModel> selEventByName(string ename, int? state)
        {
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetEventsModelByName(ename, state);
        }
        //mff
        //根据活动eid 获取该活动信息
        public EventsModel selEvent(int eid)
        {
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.GetEventsModelByID(eid);
        }

        //修个单个活动的发布状态
        public void modPubOne(int eid)
        {
            List<int?> list = new List<int?>();
            list.Add(eid);

            IDALEvents use = EventsDALFactory.Create(LanguageID);

            EventsModel model = use.GetEventsModelByID(eid); //查看该活动的当前发布状态
            if (model.State > 0) //该活动的当前为发布状态
            {
                use.UnPublish(list);
                //设置为该活动的state为0 不发布 (传递参数 eid 和 int=0)
            }
            else
            {
                use.Publish(list);
                //设置该活动的state为1 发布     (传递参数 eid 和 int=1)
            }
        }
        ////设置单个活动是否为特色活动
        public void modSetSpecial(int eid)
        {
            List<int?> list = new List<int?>();
            list.Add(eid);

            IDALEvents use = EventsDALFactory.Create(LanguageID);

            EventsModel model = use.GetEventsModelByID(eid); //查看该特色是否为特色活动
            if (model.IsSpecial > 0) //该活动是否为特色活动
            {
                use.SetNotSpecial(list);
                //设置为该活动的isSpecial为0 非特色活动 (传递参数 eid 和 int=0)
            }
            else
            {
                use.SetIsSpecial(list);
                //设置该活动的isSpecial为1 特色活动     (传递参数 eid 和 int=1)
            }
        }
        //删除单个活动的数据(目前页面过来的id是 string)
        public ResultInfo delEvent(int eid)
        {
            IList<int?> list = new List<int?>();
            list.Add(eid);
            IDALEvents use = EventsDALFactory.Create(LanguageID);
            return use.Delete(list);
        }

        public PagingList GetFilteredEventsModels(string artFormIDs, string yearMonth, string dates, string cityIDs, int currengPageIndex)
        {
            int pageSize = 12;
            PagingParameter pagingParams = PagingParameterFactory.CreateInstance(true, currengPageIndex, pageSize, null);
            PagingList models = EventsDALFactory.Create(LanguageID).GetFilteredEventsModels(artFormIDs, yearMonth, dates, cityIDs, pagingParams);
            return models;
        }

        /// <summary>
        ///     生成活动详情页HTML
        /// </summary>
        /// <param name="model"></param>
        public ResultInfo GenerateHtml(BaseModel baseModel, string dir)
        {
            ResultInfo result = new ResultInfo(false);
            string html = GetHtml(baseModel);
            if (string.IsNullOrEmpty(html)) return result;

            try
            {
                string filename = System.Web.HttpContext.Current.Server.MapPath("~" + dir + "/") + ((EventsModel)baseModel).ID.Value + ".html";
                FileUtil.SaveHtmlFile(filename, html);
                result.Result = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }

            return result;
        }

        public string GetHtml(BaseModel baseModel)
        {
            string html = null;
            EventsModel model = (EventsModel)baseModel;
            if (model.TemplateID > 0)
            {
                //生成HTML
                CmsVoWrapper vo = new CmsVoWrapper();
                vo.LanguageID = this.LanguageID;
                vo.Aid = model.ID.Value;
                vo.IsHtmlFile = true;
                vo.EventsModel = model;
                vo.Tid = model.TemplateID.Value;
                vo.Cid = model.ColumnID;
                html = CmsProxy.GetHtml(vo);
            }

            return html;
        }

        public BaseModel GetModelByID(int id)
        {
            return selEvent(id);
        }

        public IList<BaseModel> GetAllStaticPublishModels()
        {
            return selectevents().Cast<BaseModel>().ToList<BaseModel>();
        }

        public IList<Document> CreateLuceneDocuments()
        {
            IList<EventsModel> models = selectevents();
            IList<Document> documents = new List<Document>();
            foreach (EventsModel model in models)
            {
                Document doc = new Document();
                doc.Add(new Field("html", model.Detail, Field.Store.YES, Field.Index.ANALYZED));
                doc.Add(new Field("title", model.Title, Field.Store.YES, Field.Index.ANALYZED));
                doc.Add(new Field("url", string.Format("/{0}/events/{1}.html", (this.LanguageID==2052) ? "cn" : "en", model.ID.Value), Field.Store.YES, Field.Index.NOT_ANALYZED));
                documents.Add(doc);
            }

            return documents;
        }

        /// <summary>
        ///     获取活动ID为eventsID的活动的相关活动数据
        /// </summary>
        /// <param name="eventsID"></param>
        /// <returns></returns>
        public IList<EventsModel> GetRelatedEvents(int? eventsID, PagingParameter pagingParams)
        {
            return EventsDALFactory.Create(this.LanguageID).GetRelatedEvents(eventsID, pagingParams);
        }

        public PagingList GetCalendarDefaultEvents(int currengPageIndex, int pageSize)
        {
            int? requestCityID = GetRequestCityID();
            PagingParameter pagingParams = PagingParameterFactory.CreateInstance(true, currengPageIndex, pageSize, null);
            return EventsDALFactory.Create(this.LanguageID).GetCalendarDefaultEvents(requestCityID, pagingParams);
        }

        /// <summary>
        ///     获取活动中的系列名称
        /// </summary>
        /// <returns></returns>
        public IList<EventsModel> GetSeriesMainEvents()
        {
            return EventsDALFactory.Create(this.LanguageID).GetSeriesMainEvents();
        }

        /// <summary>
        ///     根据一个活动ID，获取和这个活动同系列的活动
        /// </summary>
        /// <param name="eventsID">活动ID</param>
        /// <param name="includeSelf">是否包含当前活动本身</param>
        /// <returns></returns>
        public IList<EventsModel> GetSeriesEvents(int? eventsID, bool includeSelf)
        {
            return EventsDALFactory.Create(this.LanguageID).GetSeriesEvents(eventsID, includeSelf);
        }

        public IList<string> GetAllPublishedEventsYearMonth()
        {
            return EventsDALFactory.Create(this.LanguageID).GetAllPublishedEventsYearMonth();
        }

        public IList<int> GetEventsStartDateInPeriod(string startDate, string endDate)
        {
            IList<int> ds = EventsDALFactory.Create(this.LanguageID).GetEventsDayInPeriod(startDate, endDate);
            return ds;
        }

        /// <summary>
        ///     将源活动的图片以及视频数据同步到目标活动
        /// </summary>
        /// <param name="source">源活动，该model需要设置LanguageID以及ID两个属性</param>
        /// <param name="destination">目标活动，该model需要设置LanguageID以及ID两个属性</param>
        public void SyncEventsAttachments(EventsModel source, EventsModel destination)
        {
            EventsImageBLL destBll = new EventsImageBLL(destination.LanguageID.Value);
            destBll.DeleteImagesByEventsID(destination.ID.Value);   // 将目标活动中现有的图片数据删除

            EventsImageBLL srcBll = new EventsImageBLL(source.LanguageID.Value);
            IList<EventsImageModel> ileim = srcBll.GetAllEventsImageModels(source.ID);  // 获取源活动中的所有图片数据
            int count = ileim.Count;
            while (count > 0)
            {
                EventsImageModel eim = ileim[count - 1];
                eim.ID = null;
                eim.LanguageID = destination.LanguageID;
                eim.EventsID = destination.ID;
                destBll.Save(eim);

                count--;
            }

            EventsVideoBLL destVideoBll = new EventsVideoBLL(destination.LanguageID.Value);
            destVideoBll.DeleteVideosByEventsID(destination.ID.Value);  // 将目标活动中现有的视频数据删除

            EventsVideoBLL srcVideoBll = new EventsVideoBLL(source.LanguageID.Value);
            IList<EventsVideoModel> ilevm = srcVideoBll.GetAllEventsVideoModels(source.ID);

            count = ilevm.Count;
            while (count > 0)
            {
                EventsVideoModel evm = ilevm[count - 1];
                evm.ID = null;
                evm.LanguageID = destination.LanguageID;
                evm.EventsID = destination.ID;
                destVideoBll.Save(evm);

                count--;
            }
        }

        /// <summary>
        ///     根据年月获取在该月有活动的城市
        /// </summary>
        /// <param name="yearMonth"></param>
        /// <returns></returns>
        public IList<DictionaryManageModel> GetEventsCitiesByYearMonth(string yearMonth)
        {
            return EventsDALFactory.Create(this.LanguageID).GetEventsCitiesByYearMonth(yearMonth);
        }

        public PagingList GetUploadFilesByEventsID(int? eventsID, PagingParameter pagingParams)
        {
            if (!eventsID.HasValue) return null;

            // 获取所有图片数据
            EventsImageBLL imageBll = new EventsImageBLL(this.LanguageID);
            IList<UploadFileModel> images = imageBll.GetPublishedEventsImageModels(eventsID).Cast<UploadFileModel>().ToList();

            EventsVideoBLL videoBll = new EventsVideoBLL(this.LanguageID);
            IList<UploadFileModel> videos = videoBll.GetPublishedEventsVideoModels(eventsID).Cast<UploadFileModel>().ToList();
            IList<UploadFileModel> unions = videos.Union<UploadFileModel>(images).Cast<UploadFileModel>().ToList();

            PagingList list = new PagingList(new List<UploadFileModel>(), 0);
            if (unions.Count == 0) return list;

            if (pagingParams == null)
            {
                list.Capacity = unions.Count;
                for (int i = 0; i < unions.Count; ++i)
                    list.List.Add(unions[i]);
            }
            else
            {
                int totalRecordCount = unions.Count;
                int iPageSize = pagingParams.PageSize;
                int iCurrentPageIndex = pagingParams.CurrentPageIndex;

                if (iPageSize == 0) return null;
                
                list.Capacity = unions.Count;
                int iStartRecordIndex = iPageSize * iCurrentPageIndex;
                int iEndRecordIndex = iPageSize * (iCurrentPageIndex + 1);
                if (iEndRecordIndex > totalRecordCount) iEndRecordIndex = totalRecordCount;

                for (int i = iStartRecordIndex; i < iEndRecordIndex; ++i)
                    list.List.Add(unions[i]);
            }

            return list;
        }

        private int? GetRequestCityID()
        {
            string cityName = null;
            int? cityID=null;
            try
            {
                string ip = HttpRequestUtil.GetClientIP();
                IpAddressSearchWebServiceSoap service = new IpAddressSearchWebServiceSoapClient();
                string[] result = service.getCountryCityByIp(ip);
                if (result.Length == 2)
                {
                    JoinedString js = new JoinedString(result[1], " ");
                    if (js.Count > 0)
                        cityName = js[0];
                }

                if (cityName != null)
                    cityID = FindCityIDInDictionary(cityName);
            }
            catch (Exception ex)
            {
                cityName = null;
                cityID = null;
            }

            return cityID;
        }

        private int? FindCityIDInDictionary(string cityName)
        {
            int? cityID = null;
            DictionaryManageBLL bll = new DictionaryManageBLL();
            IList cities = bll.GetDictionary(393);
            foreach (DictionaryManageModel city in cities)
            {
                if (city.Cnname == cityName || cityName.StartsWith(city.Cnname) || city.Cnname.StartsWith(cityName))
                {
                    cityID = city.Cid;
                    break;
                }
            }

            return cityID;
        }
    }
}
